package com.zhouzi.zhaoyang.ui.activity

import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.Toast
import com.google.gson.Gson
import com.google.zxing.integration.android.IntentIntegrator
import com.neovisionaries.ws.client.WebSocket
import com.neovisionaries.ws.client.WebSocketAdapter
import com.neovisionaries.ws.client.WebSocketException
import com.neovisionaries.ws.client.WebSocketFactory
import com.orhanobut.logger.Logger
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.*
import com.zhouzi.zhaoyang.config.JobFinal
import com.zhouzi.zhaoyang.config.SharedPreferencesFinal
import com.zhouzi.zhaoyang.http.HttpConfig
import com.zhouzi.zhaoyang.mvp.p.PayActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.IPayActivityView
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.*
import kotlinx.android.synthetic.main.activity_pay.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Created by ZhouZi on 2019/10/11.
 * time:11:56
 * ----------Dragon be here!----------/
 * 　　　┏┓　　 ┏┓
 * 　　┏┛┻━━━┛┻┓━━━
 * 　　┃　　　　　 ┃
 * 　　┃　　　━　  ┃
 * 　　┃　┳┛　┗┳
 * 　　┃　　　　　 ┃
 * 　　┃　　　┻　  ┃
 * 　　┃　　　　   ┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛━━━━━
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━━━━━━神兽出没━━━━━━━━━━━━━━
 */
class PayActivity : BaseActivity(), IPayActivityView {
    override fun errorToken() {
        exitToLogin()
    }

    override fun createScanOrderSuccess(createQRBean: CreateQRBean?) {
        val qrBitmap = EncodingHandler.createQRCode(createQRBean?.qrUrl, SizeUtils.dp2px(200f))
        ivQR.setImageBitmap(qrBitmap)
        outTradeNo = createQRBean!!.outTradeNo
    }

    override fun createScanOrderFailed(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT)
    }

    override fun payDepositorderSuccess(authCodeBean: AuthCodeBean) {

        val map = mutableMapOf(
                Pair("appid", authCodeBean.appid),
                Pair("mch_id", authCodeBean.mchId),
                Pair("store_id", authCodeBean.storeId),
                Pair("authinfo", authCodeBean.authinfo),
                Pair("payresult", "SUCCESS")
        )
        WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                finish()
            }
        })
        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "交易成功")
        startService(intent)


        p.getOrder(authCodeBean.outTradeNo)

    }

    override fun payDepositorderFailed(authCodeBean: AuthCodeBean) {

        val map = mutableMapOf(
                Pair("appid", authCodeBean.appid),
                Pair("mch_id", authCodeBean.mchId),
                Pair("store_id", authCodeBean.storeId),
                Pair("authinfo", authCodeBean.authinfo),
                Pair("payresult", "ERROR")
        )
        WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "交易失败")
                startService(intent)
            }
        })
    }

    override fun getmemberPaySuccess(data: BalancePaymentBean?, authCodeBean: AuthCodeBean?) {


        data?.let {
            if (data.status == 1) {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "交易成功")
                startService(intent)

                val success = Intent(mContext, PayOrderSuccessActivity::class.java)
                success.putExtra("data", data)
                startActivity(success)

                p.getOrder(authCodeBean!!.outTradeNo)


            } else {

                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", it.msg)
                startService(intent)

                val notSufficient = Intent(mContext, NotSufficientFundsActivity::class.java)
                notSufficient.putExtra("data", data)
                startActivity(notSufficient)


            }

        }


    }


    override fun getmemberPayFailed(msg: String?) {

        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", msg)
        startService(intent)

        tvVipPay.visibility = GONE


    }

    var finishActivity = true
    override fun getOrderSuccess(orderDetail: OrderDetailBean?) {
        orderDetail?.let {

            val paySuccess = Intent(mContext, PayOrderSuccessActivity::class.java)
            paySuccess.putExtra("webSocketMoney",yuan)
            paySuccess.putExtra("storeName",orderDetail.storeName)
            startActivity(paySuccess)

            printProductInformation(orderDetail)
            MyHttp.report(orderDetail)

            if (finishActivity) {
                finish()
            }
//            val activity = Intent(mContext, MainActivity::class.java)
//            startActivity(activity)

        }

    }


    override fun getOrderFailed(msg: String?) {

    }


    public fun printProductInformation(orderDetail: OrderDetailBean) {

        App.instance().printOrderWithNormal(orderDetail)

    }


    private fun putEntity(
            intent: Intent,
            orderDetail: OrderDetailBean
    ) {
        intent.putExtra("storeName", orderDetail.storeName)
        intent.putExtra("realFee", orderDetail.realFee)
    }


    private fun getUsbDeviceList(): MutableList<UsbDevice> {
        val usbDevices = mutableListOf<UsbDevice>()
        val usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        val devices = usbManager.deviceList
        val deviceIterator = devices.values.iterator()
        if (devices.size > 0) {
            while (deviceIterator.hasNext()) {
                val usbDevice = deviceIterator.next()
                if (checkUsbDevicePidVid(usbDevice))
                    usbDevices.add(usbDevice)
            }
        }
        return usbDevices
    }

    private fun checkUsbDevicePidVid(dev: UsbDevice): Boolean {
        val pid = dev.productId
        val vid = dev.vendorId
        return (vid == 34918 && pid == 256 || vid == 1137 && pid == 85
                || vid == 6790 && pid == 30084
                || vid == 26728 && pid == 256 || vid == 26728 && pid == 512
                || vid == 26728 && pid == 256 || vid == 26728 && pid == 768
                || vid == 26728 && pid == 1024 || vid == 26728 && pid == 1280
                || vid == 26728 && pid == 1536)
    }

    var vip: Boolean = true

    private val p = PayActivityPresenter()
    private var money = 0L
    private var job: Job? = null
    private var socket: WebSocket? = null

    private var sno = ""
    private var memberPrice: String = ""
    private var mobile: String = ""
    private var orderNo: String = ""
    private var outTradeNo: String = ""
    private var dialog: InputPhoneDialog? = null
    private var facePay: Boolean = true

    init {
        p.attachView(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_pay
    }


    var minus = 156
    var back = 67
    var enter = 160
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {

        if (event?.keyCode == back) {
            finish()
        }

        if (event?.action != KeyEvent.ACTION_UP) {

            if (event?.keyCode == minus) {
                finish()
            } else {
                return super.dispatchKeyEvent(event)

            }

        }
        Logger.e("keyCode:--------"+event?.keyCode)

        if ((event?.keyCode == KeyEvent.KEYCODE_ENTER || event?.keyCode == enter)){
            tvPayCode.visibility = VISIBLE
            goodsNo = tvPayCode.text.toString().trim()
            payOrder()
            Logger.e(goodsNo)

            return  false
        }

        return super.dispatchKeyEvent(event)
    }

    var cashPledge: String = "0"
    var cash = 0L
    var yuan = "0"
    var scanJudge = false
//    var personInfo
    override fun initView() {


        sno = Build.SERIAL

//         personInfo = intent.getParcelableExtra<LoginBean>("personInfo")



        if (intent.getStringExtra("money") != null && !intent.getStringExtra("money").equals("")) {

            yuan = intent.getStringExtra("money")

            if (yuan?.toDouble() > 0) {
                money = Calculator.yuan2Fen(yuan)
                createQr()
            }


            var moneyMode = SPUtils.getInstance().getValue("moneyMode", -1)
            if (moneyMode == 2) {
                // todo
                ivQR.visibility = GONE
//                scan(this)
                scanJudge = true
                tvPayCode.visibility = VISIBLE
            }

        }

        if (intent.getStringExtra("cashPledge") != null && !intent.getStringExtra("cashPledge").equals("")) {

            cashPledge = intent.getStringExtra("cashPledge")

            if (cashPledge?.toDouble() > 0) {
                cash = Calculator.yuan2Fen(cashPledge)
            }
        }


        if (intent.getStringExtra("money") != null && !intent.getStringExtra("money").equals("")) {
            tvApShowMoney.text = "原价：" + yuan + "元"
        }

        if (intent.getStringExtra("cashPledge") != null && !intent.getStringExtra("cashPledge").equals("")) {
            tvApShowMoney.text = (yuan.toDouble() + cashPledge.toDouble()).toString()
        }

        viewClick()


        /*初始化刷脸*/
        WxPayFace.getInstance().initWxpayface(mContext, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (isSuccessInfo(p0)) {

                        if (scanJudge) {
                            wxScan()
                        }

                        tvApFacePay.isEnabled = true
                        tvApFacePay.background = resources.getDrawable(R.drawable.shape_1aad19_5dp)

                        if (!yuan.equals("") || !cashPledge.equals("")) {

                            if (cashPledge.toDouble() > 0 && yuan.toDouble() > 0) {

                                getRawData()


                            }
                        } else {

                            val intent = Intent(mContext, VoiceService::class.java)
                            intent.putExtra("voiceStr", "请正确输入消费金额和押金")
                            startService(intent)

                        }

                    } else {
                        Toast.makeText(mContext, "初始化失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })


    }


    public fun scan(activity: BaseActivity) {

        val intent = Intent(App.mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "请对准条码")
        startService(intent)


        IntentIntegrator(activity)
                .setCaptureActivity(MyScanActivity().javaClass)
                .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                .setPrompt("请对准二维码")// 设置提示语
                .setCameraId(0)// 选择摄像头,可使用前置或者后置
                .setBeepEnabled(false)// 是否开启声音,扫完码之后会"哔"的一声
                .setBarcodeImageEnabled(true)// 扫完码之后生成二维码的图片
                .initiateScan()// 初始化扫码

    }

    var goodsNo = "0"
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        var result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)


        if (result != null) {

            if (result.getContents() == null) {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "扫码失败")
                startService(intent)
            } else {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "扫码成功")
                startService(intent)
                goodsNo = result.contents
                payOrder()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }

    }

    var deviceNO = Build.SERIAL
    private fun payOrder() {

        var map = mutableMapOf(
                Pair("faceCode", goodsNo),
                Pair("deviceNo", deviceNO),
                Pair("totalFee", money.toString())
        )
        p.payOrder(map, null)
    }

    private fun createQr() {

        var map = mutableMapOf(
                Pair("deviceNo", deviceNo),
                Pair("totalFee", money)
        )
        connectSocket(map)
    }


    var deviceNo = Build.SERIAL
    private fun connectSocket(map: MutableMap<String, Any?>) {
        socket = WebSocketFactory().createSocket(
                HttpConfig.WebSocket_URL + deviceNo,
                10000

        )
        socket?.addListener(object : WebSocketAdapter() {

            override fun onConnected(
                    websocket: WebSocket?,
                    headers: MutableMap<String, MutableList<String>>?
            ) {
                Handler(Looper.getMainLooper()).post {
                    Logger.d("socket连接成功")
                    /*生成二维码*/
                    p.createScanOrder(map)

                }
            }


            override fun onTextMessage(websocket: WebSocket?, text: String?) {

                Handler(Looper.getMainLooper()).post {

                    val bean = Gson().fromJson(text, GetOrderBean::class.java)

                    Log.e(
                            "webSocket:",
                            text + "\n" + bean.toString() + ":::::" + GetOrderBean(
                                    null,
                                    null
                            ).toString()
                    )

                    if (outTradeNo == bean.outTradeNo) {
                        if (bean.type == "scan-paying-notice") {
                            if (!loadDialog.isShowing) {
                                loadDialog.setContent("扫码支付中")
                                loadDialog.setCanceledOnTouchOutside(true)
                                loadDialog.show()
                                countDown()

                            }
                        } else {
                            if (bean != null && bean.status!!) {
                                val intent = Intent(mContext, VoiceService::class.java)
                                intent.putExtra("voiceStr", "交易成功")
                                startService(intent)
                                // 关闭socket
                                socket?.sendClose()
                                finishActivity = false
                                p.getOrder(bean.outTradeNo)

                                if (loadDialog.isShowing) {
                                    loadDialog.dismiss()
                                }
                            }
                        }
                    }
                }
            }

            override fun onConnectError(websocket: WebSocket?, exception: WebSocketException?) {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "服务器连接失败，请使用刷脸支付")
                startService(intent)
            }
        })
        socket?.connectAsynchronously()
    }


    override fun getMemberPriceSuccess(price: VipPriceBean, mobile: String) {
        memberPrice = price.memberFee!!
        this.mobile = mobile;
        genQRCode(orderNo)
        var totalFee = Calculator.fen2Yuan(price.totalFee!!.toLong())
        tvApShowMoney.text = "原价:" + totalFee

//        vipPrice.visibility = View.VISIBLE
        var memberFee = Calculator.fen2Yuan(price.memberFee.toLong())
//        vipPrice.text = "会员价:" + memberFee

        tvVipPay.visibility = View.GONE


    }

    override fun getMemberPriceFailed(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    private fun genQRCode(orderNo: String) {
        var url =
                HttpConfig.BASE_URL + HttpConfig.SCAN_PAY_ORDER +
                        "?deviceNo=${Build.SERIAL}&totalFee=$money&accessToken=${SPUtils.getInstance().getValue(
                                SharedPreferencesFinal.TOKEN,
                                ""
                        ) as String}&outTradeNo=$orderNo"
        if (!TextUtils.isEmpty(memberPrice)) {
            url += "&memberFee=$memberPrice"
        }
        if (!TextUtils.isEmpty(mobile)) {
            url += "&phone=$mobile"
        }
        val qrBitmap = EncodingHandler.createQRCode(url, SizeUtils.dp2px(200f))
    }

    private fun viewClick() {

        btn.setOnClickListener {

            wxScan()


        }

        tvApBtn.setOnClickListener { finish() }


        tvApFacePay.setOnClickListener {
            getRawData()
        }

        tvMorePaymentMethods.setOnClickListener {

            var intent = Intent(this, PaymentMethodsActivity::class.java)
            intent.putExtra("money", yuan)
            startActivity(intent)

        }





        tvVipPay.setOnClickListener {

            /*获取数据：rawData*/
            WxPayFace.getInstance().getWxpayfaceRawdata(object : IWxPayfaceCallback() {
                override fun response(p0: MutableMap<Any?, Any?>?) {
                    Handler(Looper.getMainLooper()).post {
                        if (isSuccessInfo(p0)) {
                            val rawData = p0?.get("rawdata").toString()
                            val map = mutableMapOf(
                                    Pair("deviceNo", sno),
//                                Pair("rawdata", rawData),
                                    Pair("rawdata", rawData)
                            )
                            facePay = false
                            p.getAuthCode(map)

                        } else {
                            Toast.makeText(mContext, "获取rawData失败，请稍后再试", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })


        }

    }

    private fun wxScan() {

        WxPayFace.getInstance().stopCodeScanner()

        val wxScanHint = Intent(App.mContext, VoiceService::class.java)
        wxScanHint.putExtra("voiceStr", "请对准上方摄像头扫码")
        startService(wxScanHint)

        WxPayFace.getInstance().startCodeScanner(object : IWxPayfaceCallback() {


            override fun response(info: MutableMap<Any?, Any?>?) {


                Log.e("startCodeScanner", info.toString())

                if (info != null) {
                    var return_code = info.get("return_code")
                    var return_msg = info.get("return_msg")
                    var code_msg = info.get("code_msg")
                    var resultString = "startCodeScanner, return_code : " + return_code + " return_msg : " + return_msg + " code_msg: " + code_msg
                    /**
                    这里添加业务自定义的工作即可 注意该回调在异步线程
                     **/

                    runOnUiThread {

                        if (!TextUtils.isEmpty(code_msg.toString())) {


                            tvPayCode.visibility  = VISIBLE
                            tvPayCode.setText( "付款码："+code_msg.toString())


                            val scanSucess = Intent(mContext, VoiceService::class.java)
                            scanSucess.putExtra("voiceStr", "扫码成功")
                            startService(scanSucess)
                            goodsNo = code_msg.toString()
                            payOrder()
                        } else {
                            val scanFaild = Intent(mContext, VoiceService::class.java)
                            scanFaild.putExtra("voiceStr", "扫码失败")
                            startService(scanFaild)
                        }


                    }



                }

            }
        })


    }


    private fun getRawData() {
        /*获取rawData*/
        WxPayFace.getInstance().getWxpayfaceRawdata(object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (isSuccessInfo(p0)) {
                        val rawData = p0?.get("rawdata").toString()
                        val map = mutableMapOf(
                                Pair("deviceNo", sno),
                                Pair("rawdata", rawData)
                        )
                        p.getAuthCode(map)

                    } else {
                        Toast.makeText(mContext, "获取rawData失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }

    /*判断回调是否异常*/
    private fun isSuccessInfo(info: Map<*, *>?): Boolean {


        if (info == null) {
            RuntimeException("调用返回为空").printStackTrace()
            return false
        }
        val code = info["return_code"] as String
        val msg = info["return_msg"] as String
        Log.d("response parameter", "response | getWxpayfaceRawdata $code | $msg")
        if (code == null || info.get("rawdata").toString() == null || !code.equals("SUCCESS")) {
            RuntimeException("调用返回非成功信息,return_msg:" + msg + "   ").printStackTrace()
            return false
        }
        return true
    }

    override fun showLoadDialog() {
        loadDialog.show()
    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()
    }

    override fun getAuthCodeSuccess(data: AuthCodeBean?) {


        data?.let {
            if (facePay) {
                val map = mutableMapOf(
                        Pair("appid", it.appid),
                        Pair("mch_id", it.mchId),
                        Pair("store_id", it.storeId),
                        Pair("out_trade_no", it.outTradeNo),
                        Pair("face_authtype", "FACEPAY"),
                        Pair("authinfo", it.authinfo),
                        Pair("ask_face_permit", "1"),
                        Pair("total_fee", money.toString()),
                        Pair("sub_appid", it.subAppId),
                        Pair("sub_mch_id", it.subMchId),
                        Pair("face_code_type", "1"),
                        Pair("ask_ret_page", "1")//是否展示微信支付成功页，可选值："0"，不展示；"1"，展示
                )
                Log.e("required parameter ", map.toString())
                WxPayFace.getInstance().getWxpayfaceCode(map, object : IWxPayfaceCallback() {
                    override fun response(p0: MutableMap<Any?, Any?>?) {

                        Log.e("response parameter ", p0.toString())

                        Handler(Looper.getMainLooper()).post {
                            if (isSuccessInfo(p0)) {
                                // 缴纳押金
                                if (cashPledge.toDouble() > 0) {
                                    val requestMap = mutableMapOf(
                                            Pair("faceCode", p0?.get("face_code") as String),
                                            Pair("deviceNo", sno),
                                            Pair("consumeFee", money.toString()),
                                            Pair("depositFee", cash.toString()),
                                            Pair("outTradeNo", data.outTradeNo),
                                            Pair("subOpenId", p0?.get("sub_openid") as String)
                                    )

                                } else {

                                    Log.e("totalFee", money.toString())
                                    val requestMap = mutableMapOf(
                                            Pair("faceCode", p0?.get("face_code") as String),
                                            Pair("deviceNo", sno),
                                            Pair("totalFee", money.toString()),
                                            Pair("outTradeNo", data.outTradeNo)
                                    )
                                    if (!TextUtils.isEmpty(memberPrice)) {
                                        requestMap["memberFee"] = memberPrice
                                    }
                                    if (!TextUtils.isEmpty(mobile)) {
                                        requestMap["phone"] = mobile
                                    }
                                    p.payOrder(requestMap, data)
                                }
                            } else {
                                Toast.makeText(mContext, "获取faceCode失败，请稍后再试", Toast.LENGTH_SHORT)
                                        .show()
                            }
                        }
                    }
                })
            } else {
                val map = mutableMapOf(
                        Pair("outTradeNo", it.outTradeNo),
                        Pair("totalFee", money.toString()),
                        Pair("outTradeNo", it.outTradeNo),
                        Pair("deviceNo", sno)
                )

                MyHttp.getUserInfo(data, map, p)
                facePay = true

            }
        }

    }

    override fun getAuthCodeFailed(msg: String) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }

    override fun payOrderSuccess(authCodeBean: AuthCodeBean?, data: String?) {


        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "交易成功")
        startService(intent)

        if (authCodeBean != null) {
            val map = mutableMapOf(
                    Pair("appid", authCodeBean.appid),
                    Pair("mch_id", authCodeBean.mchId),
                    Pair("store_id", authCodeBean.storeId),
                    Pair("authinfo", authCodeBean.authinfo),
                    Pair("payresult", "SUCCESS")
            )
            WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
                override fun response(p0: MutableMap<Any?, Any?>?) {
                   finish()
                }
            })


            p.getOrder(authCodeBean.outTradeNo)
        } else {
            p.getOrder(data)

        }

    }

    override fun payOrderFailed(msg: String, authCodeBean: AuthCodeBean?) {

        tvPayCode.setText("")

        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "交易失败")
        startService(intent)

        job?.cancel()

        if (authCodeBean != null) {
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()

            val map = mutableMapOf(
                    Pair("appid", authCodeBean.appid),
                    Pair("mch_id", authCodeBean.mchId),
                    Pair("store_id", authCodeBean.storeId),
                    Pair("authinfo", authCodeBean.authinfo),
                    Pair("payresult", "ERROR")
            )
            WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
                override fun response(p0: MutableMap<Any?, Any?>?) {

                }
            })
        }

    }


    override fun getOrderNoSuccess(orderNo: String) {
        this.orderNo = orderNo
    }

    override fun getOrderNoFailed(msg: String) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }

    override fun onStart() {
        super.onStart()

        tvPayCode.requestFocus()


        vip = SPUtils.getInstance().getValue("vip", true) as Boolean

        if (vip) {
            tvVipPay.visibility = VISIBLE
        } else {
            tvVipPay.visibility = GONE
        }


    }

    private fun countDown() {
        /*开始倒计时30s退出页面*/
        job = GlobalScope.launch {
            delay(JobFinal.EXECUTE_TIME)
            val intent = Intent(mContext, VoiceService::class.java)
            intent.putExtra("voiceStr", "交易失败")
            startService(intent)
            finish()
        }
    }

    override fun onStop() {
        super.onStop()
        job?.cancel()
    }


    override fun onDestroy() {
        super.onDestroy()
        job?.cancel()
        dialog?.dismiss()
        p.detachView()
        WxPayFace.getInstance().releaseWxpayface(mContext)
        if (loadDialog.isShowing) {
            loadDialog.dismiss()
        }
        socket?.sendClose()
        Calculator.reset()
        WxPayFace.getInstance().stopCodeScanner()

    }

}